const { query } = require('../config/database');
const cryptoUtil = require('../utils/crypto');

class User {
    constructor(userData) {
        this.openid = userData.openid;
        this.encryptedData = userData.encryptedData;
        this.salt = userData.salt;
        this.nickname = userData.nickname;
        this.avatarUrl = userData.avatarUrl;
    }

    // 创建用户
    static async create(userData) {
        try {
            const { openid, userInfo, secretKey } = userData;

            // 生成盐值
            const salt = cryptoUtil.generateSalt();

            // 加密用户数据
            const encryptedData = cryptoUtil.encryptObject(userInfo, secretKey);

            const sql = `
        INSERT INTO users (openid, encrypted_data, salt, nickname, avatar_url)
        VALUES (?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
        encrypted_data = VALUES(encrypted_data),
        nickname = VALUES(nickname),
        avatar_url = VALUES(avatar_url),
        last_login = CURRENT_TIMESTAMP
      `;

            const params = [
                openid,
                encryptedData,
                salt,
                userInfo.nickName || '',
                userInfo.avatarUrl || ''
            ];

            const result = await query(sql, params);
            return result;
        } catch (error) {
            console.error('创建用户失败:', error);
            throw error;
        }
    }

    // 根据openid查找用户
    static async findByOpenid(openid) {
        try {
            const sql = 'SELECT * FROM users WHERE openid = ? AND status = 1';
            const results = await query(sql, [openid]);
            return results.length > 0 ? results[0] : null;
        } catch (error) {
            console.error('查找用户失败:', error);
            throw error;
        }
    }

    // 更新用户信息
    static async update(openid, userData, secretKey) {
        try {
            const encryptedData = cryptoUtil.encryptObject(userData, secretKey);

            const sql = `
        UPDATE users 
        SET encrypted_data = ?, nickname = ?, avatar_url = ?, updated_at = CURRENT_TIMESTAMP
        WHERE openid = ?
      `;

            const params = [
                encryptedData,
                userData.nickName || '',
                userData.avatarUrl || '',
                openid
            ];

            const result = await query(sql, params);
            return result;
        } catch (error) {
            console.error('更新用户失败:', error);
            throw error;
        }
    }

    // 删除用户
    static async delete(openid) {
        try {
            const sql = 'UPDATE users SET status = 0 WHERE openid = ?';
            const result = await query(sql, [openid]);
            return result;
        } catch (error) {
            console.error('删除用户失败:', error);
            throw error;
        }
    }

    // 保存用户隐私数据
    static async savePrivacyData(userId, dataType, content, secretKey) {
        try {
            const encryptedContent = cryptoUtil.simpleEncrypt(content, secretKey);
            const iv = cryptoUtil.generateSalt();

            const sql = `
        INSERT INTO user_privacy_data (user_id, data_type, encrypted_content, iv)
        VALUES (?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
        encrypted_content = VALUES(encrypted_content),
        iv = VALUES(iv),
        updated_at = CURRENT_TIMESTAMP
      `;

            const params = [userId, dataType, encryptedContent, iv];
            const result = await query(sql, params);
            return result;
        } catch (error) {
            console.error('保存隐私数据失败:', error);
            throw error;
        }
    }

    // 获取用户隐私数据
    static async getPrivacyData(userId, dataType, secretKey) {
        try {
            const sql = 'SELECT * FROM user_privacy_data WHERE user_id = ? AND data_type = ?';
            const results = await query(sql, [userId, dataType]);

            if (results.length > 0) {
                const data = results[0];
                const decryptedContent = cryptoUtil.simpleDecrypt(data.encrypted_content, secretKey);
                return {
                    ...data,
                    decrypted_content: decryptedContent
                };
            }

            return null;
        } catch (error) {
            console.error('获取隐私数据失败:', error);
            throw error;
        }
    }

    // 记录操作日志
    static async logOperation(userId, operation, details, ipAddress) {
        try {
            const sql = `
        INSERT INTO operation_logs (user_id, operation, details, ip_address)
        VALUES (?, ?, ?, ?)
      `;

            const params = [userId, operation, JSON.stringify(details), ipAddress];
            const result = await query(sql, params);
            return result;
        } catch (error) {
            console.error('记录操作日志失败:', error);
            throw error;
        }
    }
}

module.exports = User;